import $ from 'jquery';
import Vue from 'vue';

let subscriptionKey = '2031edb0e6f84ccfb9e30ec36e994cdf';

let host = 'https://api.cognitive.microsofttranslator.com';
let path = '/translate?api-version=3.0';

let get_guid = function() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random() * 16 | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
};

var Translate = function(str, from, to, callback) {
	
	let params = '&to=' + to;
	
	let postData = [{
		text: str
	}];
	
	Vue.prototype.axios.post(path + params, postData, {
		headers: {
			'Content-Type': 'application/json',
			'Ocp-Apim-Subscription-Key': subscriptionKey,
			'X-ClientTraceId': get_guid()
		}
	}).then(response => {
		var ress = response.data;
		var result = '';
		for(let i = 0; i < ress.length; i++) {
			let res = ress[i];
			let translations = res.translations;
			for(let j = 0; j < translations.length; j++) {
				let translation = translations[j];
				result += translation.text;
			}
		}
		callback(result);
	}).catch(error => {
		let response = error.response;
		if(response.data.error) {
			Vue.prototype.$Message.warning('bing 翻译失败:' + response.data.error.message);
		} else {
			Vue.prototype.$Message.warning('bing 翻译失败:' + response.statusText);
		}
	});
};
export default Translate;